package com.ydcycloud.sys.service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import com.ydcycloud.sys.util.JsonUtils;

public class AreaCodeUtil {
	
	private static Map<String, Map> map;
	private static AreaCodeUtil instance = new AreaCodeUtil();
	
	private AreaCodeUtil () {
		String path = getClass().getClassLoader().getResource("areaMap.json").toString();
		path = path.replace("\\", "/");
		if (path.contains(":")) {
			path = path.replace("file:/", "");
		}
        
		try {
            String input = FileUtils.readFileToString(new File(path), "UTF-8");
            map = JsonUtils.json2Obj(input, Map.class);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	
	public static String getName(String code) {
		
		Map<String, Object> area = map.get(code);
		
		if (area == null) {
			return null;
		}
		
		return (String) area.get("name");
	}
	
	/**
	 * 获取全名 广东省 佛山市 禅城区
	 * @param code
	 * @return String
	 */
	public static String getFullname(String code) {
		Map<String, Object> area = map.get(code);
		if (area == null) return null;
		
		String fullname = (String) area.get("name");
		Map<String, Object> parent = map.get((String)area.get("parent"));
		
		while (parent != null) {
			fullname = parent.get("name") + " " + fullname;
			parent = map.get(parent.get("parent"));
		}
		
		return fullname;
	}
	
	/**
	 * 获取下一级的地区列表
	 * @param code
	 * @return List<Map<String, Object>>
	 */
	public static List<Map<String, Object>> getSub(String code) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> area = map.get(code);
		List<String> sub =  (List<String>) area.get("sub");
		
		for (String subCode: sub) {
			Map<String, Object> subItem = map.get(subCode);
			Map<String, Object> subItemCopy = new HashMap<String, Object>();
			subItemCopy.put("name", subItem.get("name"));
			subItemCopy.put("code", subCode);
			list.add(subItemCopy);
			
		}
		
		return list;
	}
}